import { resolve } from 'path'
import { loadEnv } from 'vite'
import type { UserConfig, ConfigEnv } from 'vite'
import Vue from '@vitejs/plugin-vue'
import VueJsx from '@vitejs/plugin-vue-jsx'
import WindiCSS from 'vite-plugin-windicss'
import progress from 'vite-plugin-progress'
import EslintPlugin from 'vite-plugin-eslint'
import { ViteEjsPlugin } from "vite-plugin-ejs"
import { mockDevServerPlugin } from "vite-plugin-mock-dev-server";
import PurgeIcons from 'vite-plugin-purge-icons'
// import VueI18nPlugin from "@intlify/unplugin-vue-i18n/vite"
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
// import DefineOptions from "unplugin-vue-define-options/vite"
import { createStyleImportPlugin, ElementPlusResolve, VxeTableResolve } from 'vite-plugin-style-import'
import { nodePolyfills } from 'vite-plugin-node-polyfills'
import copy from 'rollup-plugin-copy'
import VueDevTools from 'vite-plugin-vue-devtools'

// https://vitejs.dev/config/
const root = process.cwd()

function pathResolve(dir: string) {
  return resolve(root, '.', dir)
}

export default ({ command, mode }: ConfigEnv): UserConfig => {
  let env = {} as any
  const isBuild = command === 'build'
  if (!isBuild) {
    env = loadEnv((process.argv[3] === '--mode' ? process.argv[4] : process.argv[3]), root)
  } else {
    env = loadEnv(mode, root)
  }
  return {
    base: env.VITE_BASE_PATH,
    plugins: [
      VueDevTools(),
      Vue({
        template: {
          compilerOptions: {
            isCustomElement: (tag) => {
              return tag.startsWith('rev-')
            }
          }
        }
      }),
      ...(command === 'serve'
        ? [
            nodePolyfills({
              exclude: ['fs'],
              protocolImports: true,
            }),
            mockDevServerPlugin(),
          ]
        : []),
      VueJsx(),
      WindiCSS(),
      progress(),
      createStyleImportPlugin({
        resolves: [ElementPlusResolve(), VxeTableResolve()],
        libs: [{
          libraryName: 'element-plus',
          esModule: true,
          resolveStyle: (name) => {
            return `element-plus/es/components/${name.substring(3)}/style/css`
          }
        }]
      }),
      EslintPlugin({
        cache: false,
        include: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx'] // 检查的文件
      }),
      // VueI18nPlugin({
      //   runtimeOnly: false,
      //   compositionOnly: true,
      //   fullInstall: true,
      //   include: [pathResolve('src/locales/**')]
      // }),
      createSvgIconsPlugin({
        iconDirs: [pathResolve('src/assets/svgs')],
        symbolId: 'icon-[dir]-[name]',
        svgoOptions: true
      }),
      PurgeIcons(),
      mockDevServerPlugin(),
      // DefineOptions(),
      ViteEjsPlugin({
        title: env.VITE_APP_TITLE
      })
    ],

    css: {
      preprocessorOptions: {
        less: {
          additionalData: '@import "./src/styles/variables.module.less";',
          javascriptEnabled: true
        }
      }
    },
    resolve: {
      // 强制 CKEditor 模块使用单一实例，避免重复打包
      dedupe: [
        '@ckeditor/ckeditor5-vue',
        '@rev-ai/ckeditor5-classic'
      ],
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.less', '.css'],
      alias: [
        // {
        //   find: 'vue-i18n',
        //   replacement: 'vue-i18n/dist/vue-i18n.esm-bundler.js'
        // },
        {
          find: /\@\//,
          replacement: `${pathResolve('src')}/`
        }
      ]
    },
    esbuild:
      mode === "development"
        ? undefined
        : {
          // 打包构建时移除 console.log
          pure: ["console.log"],
          // 打包构建时移除 debugger
          drop: ["debugger"],
          // 打包构建时移除所有注释
          legalComments: "none"
        },
    build: {
      minify: 'esbuild',
      outDir: env.VITE_OUT_DIR || 'dist',
      sourcemap: env.VITE_SOURCEMAP === 'true' ? false : false,
      // 是否开启 gzip 压缩大小报告，禁用时能略微提高构建性能
      reportCompressedSize: false,
      // brotliSize: false,
      rollupOptions: {
        output: {
          // 将 CKEditor 统一打包到单一 chunk，避免重复模块
          manualChunks: {
            'ckeditor': [
              '@ckeditor/ckeditor5-vue',
              '@rev-ai/ckeditor5-classic'
            ]
          },
          chunkFileNames: "static/js/[name]-[hash].js",
          entryFileNames: "static/js/[name]-[hash].js",
          assetFileNames: "static/[ext]/[name]-[hash].[ext]"
        }
      }
    },
    server: {
      port: 8090,
      proxy: {
        "/api": {
          target: `http://${env.VITE_API_BASE_HOST}`,
          ws: false
          // secure: false,
          // changeOrigin: true,
        },
        "/data": {
          target: `http://${env.VITE_API_BASE_HOST}`,
          ws: false
        },
        "/rtsp": {
          target: `ws://${env.VITE_API_BASE_HOST}`,
          ws: true
        }
      },
      hmr: {
        overlay: false
      },
      host: '0.0.0.0'
    },
    optimizeDeps: {
      include: [
        'vue',
        'vue-router',
        'pinia',
        'vue-types',
        'element-plus/es/locale/lang/zh-cn',
        'element-plus/es/locale/lang/en',
        '@iconify/iconify',
        '@vueuse/core',
        'axios',
        'qs',
        'echarts',
        'echarts-wordcloud',
        'intro.js',
        'qrcode',
        '@wangeditor/editor',
        '@wangeditor/editor-for-vue'
      ],
      exclude: ['@antv/x6', 'jspdf', 'html2canvas', 'exceljs'] // 排除已知大依赖
    }
  }
}
